// pages/searchDevice/searchDevice.js
const app = getApp()
import Bluetooth from '../../utils/bluetooth'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,   // 设备列表弹窗的 显示/隐藏
    devices: [],    // BLE设备列表数据
    deviceId: '',
    serviceId: '',
    characteristicId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let systemInfo = wx.getSystemInfoSync()
    let height = systemInfo.windowHeight
    console.warn('设备高度--px7', systemInfo.screenHeight)
    this.setData({
      height
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.openBluetoothAdapter()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onHide: function () {
    clearTimeout(this.timeOut)
  },
  // 点击隐藏设备列表弹窗
  hidePopup() {
    this.setData({
      popupShow: false
    })
  },
  // 搜索附近低功耗BLE蓝牙设备
  openBluetoothAdapter() {
    let _loadingCount = 1, title = '正在搜索中...'
    wx.showLoading({
      title,
    }).then((res) => {
      this.timeOut = setTimeout(() => {
        wx.navigateTo({
          url: '/pages/searchDeviceError/searchDeviceError',
        })
      }, 60000)
    })
    Bluetooth.foundBluetoothDevices((res) => {
      let devices = this._handleFounDevices(res)   // 将搜索到的设备信息push进devices数组
      // console.error('设备数据', devices)
      if(devices.length > 0) {
        clearTimeout(this.timeOut)    // 关闭上面定义的延时定时器
        this.setData({
          popupShow: true,
          devices
        })
      }
      if(_loadingCount == 1) {
        _loadingCount = 0
        wx.hideLoading({
          complete:()=>{
            //your code
          }
        })
      }
    })
  },
  // 处理搜索到的蓝牙设备,处理
  _handleFounDevices(res) {
    const devices = this.data.devices
    res.forEach((item) => {
      const idx = Bluetooth.inArray(devices, 'deviceId', item.deviceId)
      if(item.name.includes('TJL-') || item.name.includes('WS8300-OTA')) {   // 智能矫姿精灵SN:55010000200100e54c
        // console.error(item, item.localName.includes('TJL-JIO'))
        item.name = '矫姿精灵' + item.name
        if(idx > -1) {
          devices[idx] = item
        } else {
          devices.push(item)
        }
      }
    })
    return devices
  },
  // 点击某一个设备进行关闭搜索附近蓝牙功能
  connect(e) {
    // this.setData({
    //   popupShow: false
    // })
    let deviceId = e.detail.currentTarget.dataset.deviceId
    console.log('点击链接', deviceId)
    Bluetooth.stopBluetoothDevicesDiscovery().then((res) => {
      // console.log('关闭附近搜索蓝牙设备成功---将准备连接的设备先存储到后台数据库并跳转至设置矫姿精灵标准姿势页面进行设置', res)

      // wx.navigateTo({
      //   url: '/pages/connectionBindingDevice/connectionBindingDevice',
      // })
      if(res.errno == 0) {
        this.connectBLE(deviceId)
      }
    }).catch((err) => {
      console.log('关闭蓝牙搜索功能失败', err)
    })
  },
  // 连接选中蓝牙
  connectBLE(deviceId) {
    console.log('链接设备Id', deviceId)
    let _loadingCount = 1, title = '连接中...'
    wx.showLoading({
      title
    })
    // await this.loadingEncapsulation(loadingTitle)
    Bluetooth.createBLEConnection(deviceId).then((res) => {
      if(_loadingCount == 1) {
        _loadingCount = 0
        wx.hideLoading({
          success: () => {
            this.getDeviceServices(deviceId)
          }
        })
      }
    }).catch((err) => {
      console.error('连接失败', err)
    })
  },
  // 获取连接蓝牙所有services(服务值)
  getDeviceServices(deviceId) {
    let _loadingCount = 1, title = '获取服务中...', serviceId = ''
    wx.showLoading({
      title
    })
    Bluetooth.getBLEDeviceServices(deviceId).then((res) => {
      console.warn('获取到该设备的所有服务值', res.services)
      res.services.forEach((item) => {
        if(item.isPrimary && item.uuid.includes('FF00')) {   // 该服务为设备主服务
          serviceId = item.uuid
          if(_loadingCount == 1) {
            _loadingCount = 0
            wx.hideLoading({
              success: () => {
                this.getDeviceCharacteristics(deviceId, serviceId)
              }
            })
          }
        }
      })
    }).catch((err) => {
      console.error('获取服务失败', err)
    })
  },
  // 获取已连接蓝牙设备某个服务中的所有特征characteristic
  async getDeviceCharacteristics(deviceId, serviceId) {
    let _loadingCount = 1, title = '获取特征值...', characteristicId = ''
    wx.showLoading({
      title
    })
    // await this.loadingEncapsulation(loadingTitle)
    Bluetooth.getBLEDeviceCharacteristics(deviceId, serviceId).then((res) => {
      console.warn('获取该(主)服务中的所有特征值', res.characteristics)
      res.characteristics.forEach((item) => {
        if(_loadingCount == 1) {
          _loadingCount = 0
          wx.hideLoading({}).then((res) => {
            this.setData({
                popupShow: false
            })
            // app.globalData.distinguish = false
            // wx.switchTab({   // 测试跳转至首页
            //   url: '/pages/home/home',
            // })
            wx.navigateTo({   // 跳转至设置标准身姿页面
              url: '/pages/connectionBindingDevice/connectionBindingDevice',
            })
          })
        }
        if(item.properties.read) {   // 开启读取低功耗蓝牙设备特征值的二进制数据
          characteristicId = item.uuid
          this.readDeviceCharacteristicValue(deviceId, serviceId, characteristicId)
        }
        if(item.properties.write) {   // 写入数据
          characteristicId = item.uuid
          app.globalData.deviceId = deviceId
          app.globalData.serviceId = serviceId
          app.globalData.writeCharacteristicId = characteristicId
          console.log('蓝牙连接成功', app.globalData.deviceId, app.globalData.serviceId, app.globalData.characteristicId)
          // this.setData({
          //   deviceId,
          //   serviceId,
          //   characteristicId
          // })
        }
        if(item.properties.notify || item.properties.indicate) {   // 启动蓝牙低功耗设备特征值变化时的 notify(通知) 功能,订阅特征
          characteristicId = item.uuid
          app.globalData.notifyCharacteristicId = characteristicId
          // this.notifyDeviceCharacteristicValueChange(deviceId, serviceId, characteristicId)
        }
      })
    }).catch((err) => {
      console.error('获取特征值失败', err)
    })
  },
  // 开启读取蓝牙设备特征值的二进制数据
  readDeviceCharacteristicValue(deviceId, serviceId, characteristicId) {

  },
  // 启动已连接低功耗蓝牙特征值变化时的 notify(通知)功能,监听蓝牙广播出来的数据
  notifyDeviceCharacteristicValueChange(deviceId, serviceId, characteristicId) {
    Bluetooth.notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId).then((res) => {
      wx.onBLECharacteristicValueChange((res) => {
        console.log('监听蓝牙低功耗设备的特征值变化事件成功', Bluetooth.ab2hex(res.value))
      })
    })
  },

  // showLoading 封装函数
  loadingEncapsulation(title) {
    wx.showLoading({
      title
    })
  }
})